import { create } from 'zustand';
import { message } from 'antd';
import React from 'react';
import {
    UserOutlined,
    VideoCameraOutlined,
    UploadOutlined,
    LogoutOutlined,
} from '@ant-design/icons';
import { getUerInfoApi } from '@/api/system/login';
import { getRoutersApi } from '@/api/system/menu';
import { setUserInfo } from '@/utils/auth';
import SvgIcon from '@/components/SvgIcon';
import icons from '@/components/SlIconSelect/icons';

interface MenuMetaInfo {
    icon: string;
    link: string;
    noCache: boolean;
    title: string;
}

// 定义 API 返回的菜单项类型
export interface ApiMenuItem {
    name: string;
    path: string;
    redirect: string;
    component: string;
    alwaysShow: string;
    hidden: boolean;
    sort: number;
    meta: MenuMetaInfo;
    children?: ApiMenuItem[];
}

export interface MenuButtonItem {
    menuField?: string;
    perms?: string;
    menuName?: string;
    menuType?: string;
    icon?: string;
}

export interface MenuRouterResponse {
    buttons: Record<any, MenuButtonItem[]>;
    routers: ApiMenuItem[]
}

// 定义路由配置类型
export interface RouteConfig {
    path: string;
    name: string;
    menuName?: string;
    icon?: React.ReactNode;
    element?: React.LazyExoticComponent<React.ComponentType<any>>;
    isProtected?: boolean;
    redirect?: string;
    children?: RouteConfig[];
}

// 定义菜单项类型
export interface MenuItem {
    key: string;
    icon: React.ReactNode;
    label: string;
    path: string;
    redirect?: string;
    children?: any[];
}

// 定义 Store 类型
interface MenuStore {
    routes: RouteConfig[];
    menuItems: MenuItem[];
    logoutItem?: MenuItem;
    buttonList?: Record<any, MenuButtonItem[]>;
    isMenuLoaded: boolean;
    isMenuLoading: boolean; // 添加加载状态标记
    getMenuItems: (onLogout?: () => void) => MenuItem[];
    getRoutes: () => RouteConfig[];
    currentRoute: RouteConfig | null;
    setCurrentRoute: (route: RouteConfig) => void;
    // 从 API 加载菜单
    loadMenuFromApi: () => Promise<void>;

    // 组件映射表
    componentMap: Record<
        string,
        React.LazyExoticComponent<React.ComponentType<any>>
    >;
}

// 为动态导入模块添加类型定义
type ComponentModule = {
    default: React.ComponentType<any>;
};

type DynamicImportFunction = () => Promise<ComponentModule>;

// 图标映射
const iconMap: Record<string, any> = {
    dashboard: <UserOutlined />,
    users: <VideoCameraOutlined />,
    products: <UploadOutlined />,
    logout: <LogoutOutlined />,
    default: (icon: string) => {
        return <SvgIcon iconClass={icon} />;
    },
};

// 组件映射（提前映射常用组件）
const defaultComponentMap: {
    Login: React.LazyExoticComponent<React.ComponentType<any>>;
    NotFound: React.LazyExoticComponent<React.ComponentType<any>>;
    Layout: React.LazyExoticComponent<React.ComponentType<any>>;
} = {
    Login: React.lazy(() => import('@/pages/Login')),
    NotFound: React.lazy(() => import('@/pages/NotFound')),
    Layout: React.lazy(() => import('@/pages/MainLayout')),
};
const modules= import.meta.glob('@/pages/**/*.tsx');
// 创建 Store
export const useMenuStore = create<MenuStore>((set, get) => ({
    // 初始路由配置（无菜单）
    routes: [],
    buttonList: {},
    menuItems: [],
    // 菜单是否已加载
    isMenuLoaded: false,
    isMenuLoading: false,
    // 组件映射表
    componentMap: defaultComponentMap,
    currentRoute: null,
    setCurrentRoute: (route) => set({ currentRoute: route }),
    // 获取菜单项（包含退出登录）
    getMenuItems: (onLogout?: any) => {
        const state = get();
        return [...state.menuItems];
    },
    // 获取路由配置
    getRoutes: () => {
        return get().routes;
    },
    // 从 API 加载菜单
    loadMenuFromApi: async () => {
        // 如果已经在加载中，或者已经加载完成，直接返回
        if (get().isMenuLoading || get().isMenuLoaded) return;

        // 设置加载状态
        set({ isMenuLoading: true });
        try {
            const userInfo = await getUerInfoApi();
            setUserInfo(userInfo.user);
            // 模拟 API 请求
            // 实际应用中应替换为真实 API 调用
            const menuResponse = await getRoutersApi();
            set({buttonList: menuResponse.buttons})
            // 转换 API 菜单项为路由配置和菜单项
            const { routes, menuItems } = transformApiMenuItems(
                menuResponse.routers,
                get().componentMap,
            );
            const firstRoute = routes.find(
                (ele: any) => ele.path === menuItems[0].redirect,
            );
            // 添加默认路由（未匹配路由重定向到仪表盘）
            routes.push({
                path: '*',
                name: firstRoute ? firstRoute.name : '未匹配',
                element: firstRoute
                    ? firstRoute.element
                    : get().componentMap.NotFound,
                redirect: firstRoute ? firstRoute.path : '',
                isProtected: true,
            });
            if (firstRoute) {
                routes.push({
                    path: '/',
                    redirect: firstRoute.path,
                    name: firstRoute.name,
                    element: firstRoute.element,
                    isProtected: true,
                });
            }
            // 更新状态
            set({
                routes,
                menuItems,
                isMenuLoaded: true,
                isMenuLoading: false,
            });
        } catch (error) {
            message.error('菜单加载失败');
            // 设置回退路由
            set({
                routes: [
                    // {
                    //     path: '/login',
                    //     name: '登录',
                    //     element: get().componentMap.Login,
                    //     isProtected: false,
                    // },
                    {
                        path: '*',
                        name: '未匹配',
                        element: get().componentMap.NotFound,
                        isProtected: true,
                    },
                ],
                menuItems: [],
                isMenuLoaded: true,
                isMenuLoading: false,
            });
        }
    },
}));

const judgeChildHasRouter = (redirect: string, child: any) => {
    const item = child.filter((ele: any) => ele.path === redirect);
    return !!item.length;
};

/**
 * 将 API 返回的菜单项转换为路由配置和菜单项
 */
function transformApiMenuItems(
    apiMenuItems: ApiMenuItem[],
    componentMap: Record<
        string,
        React.LazyExoticComponent<React.ComponentType<any>>
    >,
): { routes: RouteConfig[]; menuItems: MenuItem[] } {
    const routes: RouteConfig[] = [];
    const menuItems: MenuItem[] = [];

    const processMenuItems = (items: ApiMenuItem[], parentPath?: string) => {
        for (const item of items) {
            const fullPath = parentPath
                ? `${parentPath}/${item.path}`.replace('//', '/')
                : item.path;
            const icon =
                item.meta.icon && icons.includes(item.meta.icon)
                    ? iconMap[item.meta.icon] || iconMap.default(item.meta.icon)
                    : null;
            const route: RouteConfig = {
                path: fullPath,
                name: item.meta.title,
                icon: icon,
                menuName: item.name
            };
            // 处理组件
            if (item.component === 'Layout') {
                // 布局组件
                route.element = componentMap.Layout;
            } else if (item.component) {
                // 页面组件 - 使用动态导入
                const componentPath = `/src/pages/${item.component}.tsx`;
                const module = modules[componentPath];
                if (module) {
                    route.element = React.lazy(module as () => Promise<{
                        default: React.ComponentType<any>;
                    }>);
                } else {
                    // 处理模块不存在的情况
                    route.element = React.lazy(
                        () => import('@/pages/NotFound'),
                    );
                }
            }
            // 处理重定向
            if (item.redirect && item.children) {
                const hasRedirect = judgeChildHasRouter(
                    item.redirect,
                    item.children,
                );
                route['redirect'] = hasRedirect
                    ? route.redirect
                    : `${route.path}/${item.children[0].path}`;
            } else {
                route['redirect'] = '';
            }

            // 递归处理子菜单
            if (item.children && item.children.length > 0) {
                route.children = [];
                processMenuItems(item.children, fullPath);
            }
            routes.push(route);
            // 创建菜单项（仅顶级菜单项）
            if (!parentPath) {
                menuItems.push({
                    key: item.name
                        ? `${item.name}`
                        : item.path.replace('/', ''),
                    icon: icon,
                    label: item.meta.title,
                    path: fullPath,
                    redirect: route.redirect,
                    children: item.children?.map((child) => ({
                        key: child.name
                            ? `${child.name}`
                            : child.path.replace('/', ''),
                        icon:
                            child.meta.icon && icons.includes(child.meta.icon)
                                ? iconMap[child.meta.icon] ||
                                  iconMap.default(child.meta.icon)
                                : null,
                        label: child.meta.title,
                        path: item.path
                            ? `${item.path}/${child.path}`
                            : child.path,
                    })),
                });
            }
        }
    };

    processMenuItems(apiMenuItems);

    return { routes, menuItems };
}
